/*
 * Copyright (c) 2008-2012
 * LANIT
 * All rights reserved.
 *
 * This product and related documentation are protected by copyright and
 * distributed under licenses restricting its use, copying, distribution, and
 * decompilation. No part of this product or related documentation may be
 * reproduced in any form by any means without prior written authorization of
 * LANIT and its licensors, if any.
 *
 * $Id$
 */

import javax.sql.DataSource;
import java.sql.*;

/**
 * todo Document type DaoEntity
 */
public class DaoEntity {

    private static final int ID = 0;
    private static final int NAME = 1;
    private static final int DESCRIPTION = 2;
    private static final String SQL_SELECT_MAX_ID = "SELECT MAX(ID) FROM Record";
    private static final String SQL_INSERT_ROW = "INSERT INTO Record (ID ,Name, Description) VALUES (?, ?, ?)";
    private static final String SQL_SELECT_BY_ID = "SELECT * FROM Record WHERE ID = ?";
    private static final String SQL_UPDATE_BY_ID = "UPDATE Record SET Name = ?, Description = ? WHERE ID = ?";
    private static final String SQL_DELETE_BY_ID = "DELETE FROM Record WHERE ID = ?";

    private DataSource dataSource;
    private Connection connection;
    private Statement statement;
    private PreparedStatement preparedStatement;
    private ResultSet resultSet;
    private int id;
    private int countRowUpdated;
    private String methodName;
    private String[] strArray;

    public DaoEntity() throws SQLException {
        this.dataSource = new DataSourceFactory().getDataSource();
        this.connection = dataSource.getConnection();
        this.strArray = new String[3];
    }

    //Нужно ли  писать методы, которые будут выполнять логику Exception? Или нужно закладывать обработку Exception в сами Exception
    /*private void checkNotUpdatedException(int countRowUpdated, int id, String methodName) {
        if (countRowUpdated == 0) {
            throw new NotUpdatedException(methodName + ": Record " + id + " is not found.");
        }
    }*/

    public int add(String strName, String strDescription) throws SQLException {

        statement = connection.createStatement();
        preparedStatement = connection.prepareStatement(SQL_INSERT_ROW);

        //get last ID
        resultSet = statement.executeQuery(SQL_SELECT_MAX_ID);

        if (resultSet.next()) {
            id = resultSet.getInt(1);
            id++;
        }

        System.out.println("id = " + id);
        statement.close();
        resultSet.close();

        preparedStatement.setInt(1, id);
        preparedStatement.setString(2, strName);
        preparedStatement.setString(3, strDescription);

        /*try {
            countRowUpdated = preparedStatement.executeUpdate();
        } catch (SQLException exception) {
            System.err.println("Insert Operation: " + exception.getMessage());
            return 0;
        }*/
        countRowUpdated = preparedStatement.executeUpdate();

        System.out.println("countRowUpdated = " + countRowUpdated);
        preparedStatement.close();
        return id;
    }

    public void update(int id, String newName, String newDescription) throws SQLException {
        methodName = "UPDATE";
        preparedStatement = connection.prepareStatement(SQL_UPDATE_BY_ID);

        preparedStatement.setInt(3, id);
        preparedStatement.setString(1, newName);
        preparedStatement.setString(2, newDescription);

        /*try {
            countRowUpdated = preparedStatement.executeUpdate();
        } catch (SQLException exception) {
            System.err.println("Update Operation id = " + id + ": " + exception.getMessage());
            return;
        }*/

        countRowUpdated = preparedStatement.executeUpdate();

        if (countRowUpdated == 0) {
            throw new NotUpdatedException(methodName + ": Record " + id + " is not found.");
        }

        /*try {
            checkNotUpdatedException(countRowUpdated, id, methodName);
        } catch (NotUpdatedException exception) {
            System.err.println(exception.getMessage());
        }*/

        System.out.println("UPDATE: countRowUpdated = " + countRowUpdated);
        preparedStatement.close();
        //return countRowUpdated;

    }

    public void remove(int id) throws SQLException {
        methodName = "REMOVE";
        preparedStatement = connection.prepareStatement(SQL_DELETE_BY_ID);
        preparedStatement.setInt(1, id);

        countRowUpdated = preparedStatement.executeUpdate();

        if (countRowUpdated == 0) {
            throw new NotUpdatedException(methodName + ": Record " + id + " is not found.");
        }
        /*try {
            checkNotUpdatedException(countRowUpdated, id, methodName);
        } catch (NotUpdatedException exception) {
            System.err.println(exception.getMessage());
        }*/
        System.out.println("REMOVE: countRowUpdated = " + countRowUpdated);
        preparedStatement.close();
    }

    public String[] getById(int id) throws SQLException {

        methodName = "getById";
        preparedStatement = connection.prepareStatement(SQL_SELECT_BY_ID);
        preparedStatement.setInt(1, id);

        resultSet = preparedStatement.executeQuery();

        if (!resultSet.next()) {
            strArray = null;
            return strArray;
        }
        strArray[ID] = String.valueOf(resultSet.getInt(1));
        strArray[NAME] = resultSet.getString(2);
        strArray[DESCRIPTION] = resultSet.getString(3);

        /*if (resultSet.next()) {
            System.out.println("resultSet = " + resultSet.getString(2));
        } else {
            System.err.println(methodName + ": Record " + id + " is not found.");
        }*/
        resultSet.close();
        preparedStatement.close();
        return strArray;
    }
}
